package cn.ll.service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.ll.po.Connector;
import cn.ll.po.ConnectorDAO;
import cn.ll.po.Contract;
import cn.ll.po.ContractDAO;

public class ConnectorService {
	ConnectorDAO dao;

	/**
	 * 存储一个contract(协议)对象
	 * 
	 * @param contract
	 */
	public void create(Connector connector) {

		if (connector.getId() != null && connector.getId().length() > 0) {
			dao.attachDirty(connector);
		} else {
			this.createConnectorId(connector);

			dao.save(connector);
		}

	}

	private void createConnectorId(Connector connector) {

		Long count = dao.countByCustomerId(connector.getCustomerid());

		DecimalFormat df = new DecimalFormat("000");

		String id = connector.getCustomerid() + "-" + df.format(++count);

		connector.setId(id);
		connector.setConnectorid(id);

	}

	public void update(Contract contract) {

	}

	/**
	 * 删除一个contract(协议)对象
	 * 
	 * @param contract
	 */
	public void delete() {
	}

	/**
	 * 
	 * @param cdt
	 * @param p
	 * @param pn
	 * @return
	 */
	public List<Connector> read(Map cdt) {

		String customerid = (String) cdt.get("customerid");
		String id = (String) cdt.get("id");

		List<Connector> lst = null;
		if (customerid != null) {
			lst = dao.findByCustomerid(customerid);
		} else {
			Connector connector = dao.findById(id);
			lst = new ArrayList<Connector>();
			lst.add(connector);
		}

		return lst;
	}

	public ConnectorDAO getDao() {
		return dao;
	}

	public void setDao(ConnectorDAO dao) {
		this.dao = dao;
	}

	public List<Map> readForSelect(Map cdt) {

		List<Connector> ls = this.read(cdt);

		List rsLs = new ArrayList<Map>();
		for (Connector connector : ls) {
			Map mp = new HashMap();
			mp.put("key", connector.getConnectorid());
			String connectroId = connector.getConnectorid();
			mp.put("value",  connectroId.substring(connectroId.length()-4, connectroId.length())+ "-" + connector.getConnectorname());
			rsLs.add(mp);
		}

		return rsLs;
	}
}
